{{template "base" .}}

{{define "content"}}
<div x-data="editCustomerData()" class="space-y-6">
    <!-- Page Header -->
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between">
        <div>
            <h1 class="text-xl font-semibold text-gray-900">编辑客户</h1>
            <p class="mt-1 text-sm text-gray-500">修改客户的基本信息和学习需求</p>
        </div>
        <div class="mt-3 sm:mt-0 flex space-x-3">
            <a :href="'/customers/' + customerId" 
               class="inline-flex items-center px-3 py-2 bg-blue-500 text-white text-sm rounded-md hover:bg-blue-600 transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
                <i class="fas fa-eye text-sm mr-2"></i>
                查看详情
            </a>
            <a href="/customers" 
               class="inline-flex items-center px-3 py-2 bg-gray-500 text-white text-sm rounded-md hover:bg-gray-600 transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2">
                <i class="fas fa-arrow-left text-sm mr-2"></i>
                返回列表
            </a>
        </div>
    </div>

    <!-- Loading State -->
    <div x-show="initialLoading" class="bg-white shadow-lg rounded-lg p-6 border border-gray-100">
        <div class="flex items-center justify-center">
            <i class="fas fa-spinner fa-spin text-2xl text-gray-400 mr-3"></i>
            <span class="text-gray-500">加载客户信息中...</span>
        </div>
    </div>

    <!-- Progress Indicator -->
    <div x-show="!initialLoading" class="bg-white rounded-md shadow-sm p-3 border border-gray-200">
        <div class="flex items-center justify-between mb-2">
            <span class="text-sm font-medium text-gray-700">编辑进度</span>
            <span class="text-sm font-semibold" :class="progress === 100 ? 'text-green-600' : 'text-blue-600'" x-text="Math.round(progress) + '%'"></span>
        </div>
        <div class="w-full bg-gray-200 rounded-full h-1.5">
            <div class="h-1.5 rounded-full transition-all duration-300 ease-out" 
                 :class="progress === 100 ? 'bg-green-500' : 'bg-blue-500'"
                 :style="'width: ' + progress + '%'"></div>
        </div>
    </div>

    <!-- Form -->
    <div x-show="!initialLoading" class="bg-white shadow-sm rounded-md border border-gray-200">
        <form @submit.prevent="submitForm()" class="space-y-0">
            <!-- 基本信息区域 -->
            <div class="px-4 py-3 border-b border-gray-200 bg-gray-50 rounded-t-md">
                <div class="flex items-center justify-between">
                    <div class="flex items-center">
                        <div class="w-6 h-6 bg-blue-500 rounded-full flex items-center justify-center mr-3">
                            <i class="fas fa-user text-white text-sm"></i>
                        </div>
                        <div>
                            <h3 class="text-sm font-medium text-gray-900">基本信息</h3>
                            <p class="text-xs text-gray-500">请修改客户的基本信息</p>
                        </div>
                    </div>
                    <div class="flex items-center space-x-4">
                        <div class="text-sm text-gray-500">
                            创建时间：<span x-text="formatDate(customer.created_at)"></span>
                        </div>
                        <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full"
                              :class="getStatusClass(customer.status)"
                              x-text="getStatusText(customer.status)"></span>
                    </div>
                </div>
            </div>
            
            <div class="px-4 py-4">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <!-- 姓名 -->
                    <div class="relative">
                        <label for="name" class="block text-sm font-medium text-gray-700 mb-1">
                            姓名 <span class="text-red-500">*</span>
                            <span class="text-gray-500 text-xs ml-1">(必填) - 请输入客户的真实姓名，用于身份识别和联系</span>
                        </label>
                        <input type="text" 
                               id="name"
                               x-model="form.name" 
                               @blur="validateField('name')"
                               @input="validateField('name')"
                               :class="getFieldClass('name')"
                               class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 hover:border-gray-400 transition-colors duration-200 text-sm"
                               placeholder="请输入客户姓名"
                               autocomplete="name">
                        <p x-show="errors.name" x-transition class="mt-1 text-xs text-red-600">
                            <span x-text="errors.name"></span>
                        </p>
                    </div>

                    <!-- 手机号 -->
                    <div class="relative">
                        <label for="phone" class="block text-sm font-medium text-gray-700 mb-1">
                            手机号 <span class="text-red-500">*</span>
                            <span class="text-gray-500 text-xs ml-1">(必填) - 请输入11位有效手机号码，用于课程通知和联系</span>
                        </label>
                        <input type="tel" 
                               id="phone"
                               x-model="form.phone" 
                               @blur="validateField('phone')"
                               @input="validateField('phone')"
                               :class="getFieldClass('phone')"
                               class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 hover:border-gray-400 transition-colors duration-200 text-sm"
                               placeholder="请输入手机号"
                               autocomplete="tel">
                        <p x-show="errors.phone" x-transition class="mt-1 text-xs text-red-600">
                            <span x-text="errors.phone"></span>
                        </p>
                    </div>

                    <!-- 微信 -->
                    <div class="relative">
                        <label for="wechat" class="block text-sm font-medium text-gray-700 mb-1">
                            微信号
                            <span class="text-gray-500 text-xs ml-1">(选填) - 客户的微信账号</span>
                        </label>
                        <input type="text" 
                               id="wechat"
                               x-model="form.wechat" 
                               @blur="validateField('wechat')"
                               :class="getFieldClass('wechat')"
                               class="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 transition-colors duration-200 text-sm"
                               placeholder="请输入微信账号">
                        <p x-show="errors.wechat" x-transition class="mt-1 text-xs text-red-600">
                            <span x-text="errors.wechat"></span>
                        </p>
                    </div>

                    <!-- 年级 -->
                    <div class="relative">
                        <label for="grade" class="block text-sm font-medium text-gray-700 mb-1">
                            年级 <span class="text-red-500">*</span>
                            <span class="text-gray-500 text-xs ml-1">(必填) - 请选择客户当前所在年级，便于匹配合适的教学内容</span>
                        </label>
                        <select id="grade"
                                x-model="form.grade" 
                                @blur="validateField('grade')"
                                @change="validateField('grade')"
                                :class="getFieldClass('grade')"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 hover:border-gray-400 transition-colors duration-200 appearance-none text-sm cursor-pointer">
                            <option value="">请选择年级</option>
                                <optgroup label="小学">
                                    <option value="小学一年级">小学一年级</option>
                                    <option value="小学二年级">小学二年级</option>
                                    <option value="小学三年级">小学三年级</option>
                                    <option value="小学四年级">小学四年级</option>
                                    <option value="小学五年级">小学五年级</option>
                                    <option value="小学六年级">小学六年级</option>
                                </optgroup>
                                <optgroup label="初中">
                                    <option value="初中一年级">初中一年级</option>
                                    <option value="初中二年级">初中二年级</option>
                                    <option value="初中三年级">初中三年级</option>
                                </optgroup>
                                <optgroup label="高中">
                                    <option value="高中一年级">高中一年级</option>
                                    <option value="高中二年级">高中二年级</option>
                                    <option value="高中三年级">高中三年级</option>
                                </optgroup>
                                <optgroup label="其他">
                                    <option value="大学">大学</option>
                                    <option value="成人">成人</option>
                                </optgroup>
                            </select>
                        <p x-show="errors.grade" x-transition class="mt-1 text-xs text-red-600">
                            <span x-text="errors.grade"></span>
                        </p>
                    </div>                 

                    <!-- 年龄 -->
                    <div class="relative">
                        <label for="age" class="block text-sm font-medium text-gray-700 mb-1">
                            年龄
                            <span class="text-gray-500 text-xs ml-1">(可选) - 请输入客户年龄，有助于制定合适的学习计划</span>
                        </label>
                        <input type="number" 
                               id="age"
                               x-model="form.age" 
                               @blur="validateField('age')"
                               @input="validateField('age')"
                               min="1"
                               max="100"
                               :class="getFieldClass('age')"
                               class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 hover:border-gray-400 transition-colors duration-200 text-sm"
                               placeholder="请输入年龄"
                               autocomplete="age">
                        <p x-show="errors.age" x-transition class="mt-1 text-xs text-red-600">
                            <span x-text="errors.age"></span>
                        </p>
                    </div>

                    <!-- 性别 -->
                    <div class="relative">
                        <label for="gender" class="block text-sm font-medium text-gray-700 mb-1">
                            性别
                            <span class="text-gray-500 text-xs ml-1">(可选) - 选择客户性别，便于安排合适的教学环境</span>
                        </label>
                        <select id="gender"
                                x-model="form.gender" 
                                @blur="validateField('gender')"
                                @change="validateField('gender')"
                                :class="getFieldClass('gender')"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 hover:border-gray-400 transition-colors duration-200 appearance-none text-sm cursor-pointer">
                            <option value="">请选择性别</option>
                            <option value="male">男</option>
                            <option value="female">女</option>
                        </select>
                    </div>

                    <!-- 城市 -->
                    <div class="relative">
                        <label for="city" class="block text-sm font-medium text-gray-700 mb-1">
                            所在城市
                            <span class="text-gray-500 text-xs ml-1">(可选) - 请选择或输入客户所在城市，便于安排就近的教学服务</span>
                        </label>
                        
                        <!-- 热门城市快速选择 -->
                        <div class="mb-2">
                            <div class="text-xs text-gray-600 mb-1">热门城市：</div>
                            <div class="flex flex-wrap gap-2">
                                <template x-for="city in ['北京', '上海', '广州', '深圳', '杭州', '南京', '苏州', '成都']" :key="city">
                                    <button type="button" 
                                            @click="form.city = city; validateField('city')"
                                            :class="form.city === city ? 'bg-blue-500 text-white shadow-md' : 'bg-white text-gray-700 hover:bg-blue-50 hover:text-blue-700 hover:shadow-md'"
                                            class="px-2 py-1 text-xs rounded-xl border shadow-sm transition-colors duration-200">
                                        <span x-text="city"></span>
                                    </button>
                                </template>
                            </div>
                        </div>
                        
                        <!-- 城市搜索输入框 -->
                        <div class="relative" x-data="{ 
                            showDropdown: false, 
                            filteredCities: [], 
                            selectedIndex: -1,
                            searchQuery: '',
                            init() {
                                this.filteredCities = this.commonCities.slice(0, 10);
                            },
                            filterCities(query) {
                                this.searchQuery = query;
                                if (!query || query.trim() === '') {
                                    this.filteredCities = this.commonCities.slice(0, 10);
                                } else {
                                    const searchTerm = query.toLowerCase().trim();
                                    this.filteredCities = this.commonCities.filter(city => 
                                        city.toLowerCase().includes(searchTerm)
                                    ).slice(0, 12);
                                }
                                this.selectedIndex = -1;
                            },
                            selectCity(city) {
                                this.form.city = city;
                                this.showDropdown = false;
                                this.validateField('city');
                                this.selectedIndex = -1;
                            },
                            handleKeydown(event) {
                                if (!this.showDropdown) return;
                                
                                switch(event.key) {
                                    case 'ArrowDown':
                                        event.preventDefault();
                                        this.selectedIndex = Math.min(this.selectedIndex + 1, this.filteredCities.length - 1);
                                        break;
                                    case 'ArrowUp':
                                        event.preventDefault();
                                        this.selectedIndex = Math.max(this.selectedIndex - 1, -1);
                                        break;
                                    case 'Enter':
                                        event.preventDefault();
                                        if (this.selectedIndex >= 0 && this.selectedIndex < this.filteredCities.length) {
                                            this.selectCity(this.filteredCities[this.selectedIndex]);
                                        }
                                        break;
                                    case 'Escape':
                                        this.showDropdown = false;
                                        this.selectedIndex = -1;
                                        break;
                                }
                            }
                        }" 
                        x-init="init()">
                            <div class="relative">
                                <input type="text" 
                                       id="city" 
                                       x-model="form.city"
                                       @input="filterCities($event.target.value); showDropdown = true; validateField('city')"
                                       @focus="showDropdown = true; filteredCities = commonCities.slice(0, 10)"
                                       @blur="setTimeout(() => showDropdown = false, 200)"
                                       @keydown="handleKeydown($event)"
                                       :class="getFieldClass('city')"
                                       class="w-full px-3 py-2 pr-10 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 hover:border-gray-400 transition-colors duration-200 text-sm"
                                       placeholder="输入城市名称搜索..."
                                       autocomplete="off">
                                
                                <!-- 搜索图标 -->
                                <div class="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                                    <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                                    </svg>
                                </div>
                            </div>
                            
                            <!-- 搜索下拉列表 -->
                            <div x-show="showDropdown && filteredCities.length > 0" 
                                 x-transition:enter="transition ease-out duration-200"
                                 x-transition:enter-start="opacity-0 transform scale-95 translate-y-1"
                                 x-transition:enter-end="opacity-100 transform scale-100 translate-y-0"
                                 x-transition:leave="transition ease-in duration-150"
                                 x-transition:leave-start="opacity-100 transform scale-100 translate-y-0"
                                 x-transition:leave-end="opacity-0 transform scale-95 translate-y-1"
                                 class="absolute z-20 w-full mt-1 bg-white border border-gray-200 rounded-lg shadow-xl max-h-64 overflow-y-auto">
                                <div class="py-1">
                                    <template x-for="(city, index) in filteredCities" :key="city">
                                        <div @click="selectCity(city)"
                                             :class="{
                                                'bg-blue-50 text-blue-700': selectedIndex === index,
                                                'text-gray-900': selectedIndex !== index
                                             }"
                                             class="px-4 py-2.5 hover:bg-blue-50 hover:text-blue-700 cursor-pointer text-sm transition-colors duration-150 flex items-center justify-between group">
                                            <span x-text="city"></span>
                                            <svg x-show="selectedIndex === index" class="w-4 h-4 text-blue-500" fill="currentColor" viewBox="0 0 20 20">
                                                <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"></path>
                                            </svg>
                                        </div>
                                    </template>
                                </div>
                            </div>
                            
                            <!-- 无搜索结果提示 -->
                            <div x-show="showDropdown && form.city && form.city.trim() && filteredCities.length === 0"
                                 x-transition
                                 class="absolute z-20 w-full mt-1 bg-white border border-gray-200 rounded-lg shadow-xl p-4">
                                <div class="flex flex-col items-center justify-center text-gray-500 text-sm">
                                    <svg class="w-8 h-8 mb-2 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                                    </svg>
                                    <div class="text-center">
                                        <div class="font-medium">未找到匹配的城市</div>
                                        <div class="text-xs text-gray-400 mt-1">请尝试其他关键词</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div x-show="errors.city" class="mt-1 text-sm text-red-600 flex items-center">
                            <svg class="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
                                <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd"></path>
                            </svg>
                            <span x-text="errors.city"></span>
                        </div>
                    </div>

                    <!-- 地址 -->
                    <div class="relative">
                        <label for="address" class="block text-sm font-medium text-gray-700 mb-1">
                            地址
                            <span class="text-gray-500 text-xs ml-1">(选填) - 客户的详细地址信息</span>
                        </label>
                        <input type="text" 
                               id="address"
                               x-model="form.address" 
                               @blur="validateField('address')"
                               :class="getFieldClass('address')"
                               class="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 transition-colors duration-200 text-sm"
                               placeholder="请输入详细地址">
                        <p x-show="errors.address" x-transition class="mt-1 text-xs text-red-600">
                            <span x-text="errors.address"></span>
                        </p>
                    </div>                    

                </div>

            </div>
            
            <!-- 学习信息区域 -->
            <div class="border-t border-gray-200">
                <div class="px-4 py-3 border-b border-gray-200 bg-gray-50">
                    <div class="flex items-center">
                        <svg class="w-4 h-4 mr-2 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.477 18.246 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"></path>
                        </svg>
                        <div>
                            <h4 class="text-sm font-medium text-gray-900">学习信息</h4>
                            <p class="text-xs text-gray-600">请修改客户的学习需求和相关信息</p>
                        </div>
                    </div>
                </div>
                
                <div class="px-4 py-4">
                    <div class="grid grid-cols-1 gap-4">
                        <!-- 科目 -->
                        <div class="relative">
                            <label for="subject" class="block text-sm font-medium text-gray-700 mb-1">
                                学习科目 <span class="text-red-500">*</span>
                                <span class="text-gray-500 text-xs ml-1">(必填) - 请选择或输入客户需要学习的科目，支持多个科目</span>
                            </label>
                            
                            <!-- 热门科目快速选择 -->
                            <div class="mb-2">
                                <div class="text-xs text-gray-600 mb-1">热门科目：</div>
                                <div class="flex flex-wrap gap-2">
                                    <template x-for="subject in ['数学', '英语', '语文', '物理', '化学', '生物']" :key="subject">
                                        <button type="button" 
                                                @click="form.subject = subject; validateField('subject')"
                                                :class="form.subject === subject ? 'bg-green-500 text-white shadow-md' : 'bg-white text-gray-700 hover:bg-green-50 hover:text-green-700 hover:shadow-md'"
                                                class="px-2 py-1 text-xs rounded-xl border shadow-sm transition-colors duration-200">
                                            <span x-text="subject"></span>
                                        </button>
                                    </template>
                                </div>
                            </div>
                            
                            <!-- 科目搜索输入框 -->
                            <div class="relative" x-data="{ 
                                showDropdown: false, 
                                filteredSubjects: [], 
                                selectedIndex: -1,
                                searchQuery: '',
                                init() {
                                    this.filteredSubjects = this.commonSubjects.slice(0, 10);
                                },
                                filterSubjects(query) {
                                    this.searchQuery = query;
                                    if (!query || query.trim() === '') {
                                        this.filteredSubjects = this.commonSubjects.slice(0, 10);
                                    } else {
                                        const searchTerm = query.toLowerCase().trim();
                                        this.filteredSubjects = this.commonSubjects.filter(subject => 
                                            subject.toLowerCase().includes(searchTerm)
                                        ).slice(0, 12);
                                    }
                                    this.selectedIndex = -1;
                                },
                                selectSubject(subject) {
                                    this.form.subject = subject;
                                    this.showDropdown = false;
                                    this.validateField('subject');
                                    this.selectedIndex = -1;
                                },
                                handleKeydown(event) {
                                    if (!this.showDropdown) return;
                                    
                                    switch(event.key) {
                                        case 'ArrowDown':
                                            event.preventDefault();
                                            this.selectedIndex = Math.min(this.selectedIndex + 1, this.filteredSubjects.length - 1);
                                            break;
                                        case 'ArrowUp':
                                            event.preventDefault();
                                            this.selectedIndex = Math.max(this.selectedIndex - 1, -1);
                                            break;
                                        case 'Enter':
                                            event.preventDefault();
                                            if (this.selectedIndex >= 0 && this.selectedIndex < this.filteredSubjects.length) {
                                                this.selectSubject(this.filteredSubjects[this.selectedIndex]);
                                            }
                                            break;
                                        case 'Escape':
                                            this.showDropdown = false;
                                            this.selectedIndex = -1;
                                            break;
                                    }
                                }
                            }" 
                                 x-init="init()">
                                <div class="relative">
                                    <input type="text" 
                                           id="subject" 
                                           x-model="form.subject"
                                           @input="filterSubjects($event.target.value); showDropdown = true; validateField('subject')"
                                           @focus="showDropdown = true; filteredSubjects = commonSubjects.slice(0, 10)"
                                           @blur="setTimeout(() => showDropdown = false, 200)"
                                           @keydown="handleKeydown($event)"
                                           :class="getFieldClass('subject')"
                                           class="w-full px-3 py-2 pr-10 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-green-500 focus:border-green-500 hover:border-gray-400 transition-colors duration-200 text-sm"
                                           placeholder="输入科目名称搜索..."
                                           autocomplete="off">
                                    
                                    <!-- 搜索图标 -->
                                    <div class="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                                        <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                                        </svg>
                                    </div>
                                </div>
                                
                                <!-- 搜索下拉列表 -->
                                <div x-show="showDropdown && filteredSubjects.length > 0" 
                                     x-transition:enter="transition ease-out duration-200"
                                     x-transition:enter-start="opacity-0 transform scale-95 translate-y-1"
                                     x-transition:enter-end="opacity-100 transform scale-100 translate-y-0"
                                     x-transition:leave="transition ease-in duration-150"
                                     x-transition:leave-start="opacity-100 transform scale-100 translate-y-0"
                                     x-transition:leave-end="opacity-0 transform scale-95 translate-y-1"
                                     class="absolute z-20 w-full mt-1 bg-white border border-gray-200 rounded-lg shadow-xl max-h-64 overflow-y-auto">
                                    <div class="py-1">
                                        <template x-for="(subject, index) in filteredSubjects" :key="subject">
                                            <div @click="selectSubject(subject)"
                                                 :class="{
                                                    'bg-green-50 text-green-700': selectedIndex === index,
                                                    'text-gray-900': selectedIndex !== index
                                                 }"
                                                 class="px-4 py-2.5 hover:bg-green-50 hover:text-green-700 cursor-pointer text-sm transition-colors duration-150 flex items-center justify-between group">
                                                <span x-text="subject"></span>
                                                <svg x-show="selectedIndex === index" class="w-4 h-4 text-green-500" fill="currentColor" viewBox="0 0 20 20">
                                                    <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"></path>
                                                </svg>
                                            </div>
                                        </template>
                                    </div>
                                </div>
                                
                                <!-- 无搜索结果提示 -->
                                <div x-show="showDropdown && form.subject && form.subject.trim() && filteredSubjects.length === 0"
                                     x-transition
                                     class="absolute z-20 w-full mt-1 bg-white border border-gray-200 rounded-lg shadow-xl p-4">
                                    <div class="flex flex-col items-center justify-center text-gray-500 text-sm">
                                        <svg class="w-8 h-8 mb-2 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                                        </svg>
                                        <div class="text-center">
                                            <div class="font-medium">未找到匹配的科目</div>
                                            <div class="text-xs text-gray-400 mt-1">请尝试其他关键词或手动输入</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div x-show="errors.subject" class="mt-1 text-sm text-red-600 flex items-center">
                                <svg class="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
                                    <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd"></path>
                                </svg>
                                <span x-text="errors.subject"></span>
                            </div>
                        </div>

                        <!-- 备注 -->
                        <div class="relative">
                            <label for="notes" class="block text-sm font-medium text-gray-700 mb-1">
                                备注信息
                                <span class="text-gray-500 text-xs ml-1">(可选) - 请输入客户的特殊需求、学习目标或其他重要信息</span>
                            </label>
                            <div class="relative">
                                <textarea id="notes"
                                          x-model="form.notes" 
                                          @blur="validateField('notes')"
                                          @input="validateField('notes')"
                                          rows="3"
                                          :class="getFieldClass('notes')"
                                          class="w-full px-3 py-2 pr-16 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 hover:border-gray-400 transition-colors duration-200 resize-none text-sm"
                                          placeholder="请输入备注信息（可选）"
                                          maxlength="200"></textarea>
                                <div class="absolute bottom-2 right-2 text-xs text-gray-400">
                                    <span x-text="form.notes ? form.notes.length : 0"></span>/200
                                </div>
                            </div>
                            <p x-show="errors.notes" x-transition class="mt-1 text-xs text-red-600">
                                <span x-text="errors.notes"></span>
                            </p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 提交按钮区域 -->
            <div class="border-t border-gray-200 bg-gray-50 px-4 py-3">
                <div class="flex flex-col sm:flex-row justify-between items-center space-y-2 sm:space-y-0 sm:space-x-2">
                    <!-- 表单状态提示 -->
                    <div class="flex items-center text-xs">
                        <div class="flex items-center" x-show="hasErrors">
                            <span class="text-red-600">请检查并修正表单中的错误</span>
                        </div>
                        <div class="flex items-center" x-show="!hasErrors && isFormValid">
                            <span class="text-green-600">表单填写完整，可以提交</span>
                        </div>
                        <div class="flex items-center" x-show="!hasErrors && !isFormValid">
                            <span class="text-blue-600">请完善必填信息</span>
                        </div>
                    </div>
                    
                    <!-- 按钮组 -->
                    <div class="flex flex-col sm:flex-row space-y-1 sm:space-y-0 sm:space-x-2">
                        <!-- 取消按钮 -->
                        <a href="/customers" 
                           class="inline-flex items-center px-4 py-2 bg-gray-500 text-white rounded-md shadow-sm hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 text-sm font-medium transition-colors duration-200">
                            取消
                        </a>
                        
                        <!-- 提交按钮 -->
                        <button type="submit" 
                                :disabled="loading || hasErrors"
                                :class="loading || hasErrors ? 'opacity-50 cursor-not-allowed' : 'hover:bg-blue-600'"
                                class="inline-flex items-center px-6 py-2 bg-blue-500 text-white rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 text-sm font-medium transition-colors duration-200">
                            <span x-text="loading ? '保存中...' : '保存修改'"></span>
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>
 
    
</div>

<script>
    function editCustomerData() {
        return {
            loading: false,
            initialLoading: true,
            customerId: null,
            customer: {},
            form: {
                name: '',
                phone: '',
                age: '',
                gender: '',
                city: '',
                grade: '',
                subject: '',
                notes: ''
            },
            errors: {},
            commonCities: [
                '北京', '上海', '广州', '深圳', '杭州', '南京', '苏州', '成都', 
                '武汉', '西安', '重庆', '天津', '青岛', '大连', '厦门', '宁波',
                '无锡', '佛山', '东莞', '长沙', '郑州', '济南', '哈尔滨', '福州',
                '石家庄', '太原', '沈阳', '长春', '南昌', '合肥', '昆明', '贵阳',
                '兰州', '银川', '西宁', '乌鲁木齐', '拉萨', '海口', '三亚', '温州',
                '嘉兴', '绍兴', '金华', '台州', '湖州', '丽水', '衢州', '舟山',
                '常州', '徐州', '盐城', '淮安', '连云港', '南通', '泰州', '宿迁',
                '镇江', '扬州', '芜湖', '蚌埠', '安庆', '黄山', '阜阳', '宿州',
                '六安', '亳州', '池州', '宣城', '滁州', '马鞍山', '淮南', '淮北'
            ],
            commonSubjects: [
                '数学', '英语', '语文', '物理', '化学', '生物', '历史', '地理',
                '政治', '音乐', '美术', '体育', '信息技术', '科学', '思想品德',
                '编程', '机器人', '奥数', '作文', '阅读理解', '口语', '书法'
            ],
            popularSubjects: ['数学', '英语', '语文', '物理', '化学', '生物'],
            
            // 城市搜索过滤方法
            filterCities(query) {
                if (!query || query.trim() === '') {
                    this.filteredCities = this.commonCities.slice(0, 10); // 显示前10个城市
                    return;
                }
                
                const searchTerm = query.toLowerCase().trim();
                this.filteredCities = this.commonCities.filter(city => 
                    city.toLowerCase().includes(searchTerm)
                ).slice(0, 8); // 最多显示8个匹配结果
            },
            
            // 计算属性
            get progress() {
                const requiredFields = ['name', 'phone', 'city', 'subject'];
                const optionalFields = ['age', 'gender', 'grade', 'notes'];
                
                const filledRequired = requiredFields.filter(field => 
                    this.form[field] && this.form[field].toString().trim()
                ).length;
                const filledOptional = optionalFields.filter(field => 
                    this.form[field] && this.form[field].toString().trim()
                ).length;
                
                // 必填字段权重70%，可选字段权重30%
                const requiredProgress = (filledRequired / requiredFields.length) * 70;
                const optionalProgress = (filledOptional / optionalFields.length) * 30;
                
                return Math.min(100, Math.round(requiredProgress + optionalProgress));
            },
            
            get hasErrors() {
                return Object.keys(this.errors).length > 0;
            },
            
            get isFormValid() {
                const requiredFields = ['name', 'phone', 'city', 'subject'];
                return requiredFields.every(field => this.form[field] && this.form[field].trim() && !this.errors[field]);
            },
            
            async init() {
                try {
                    // 从URL获取客户ID
                    const pathParts = window.location.pathname.split('/');
                    this.customerId = pathParts[pathParts.length - 2]; // /customers/{id}/edit
                    
                    if (!this.customerId || this.customerId === 'edit') {
                        this.showNotification('无效的客户ID', 'error');
                        setTimeout(() => window.location.href = '/customers', 1500);
                        return;
                    }
                    
                    // 加载客户数据
                    await this.loadCustomer();
                    
                    // 添加键盘快捷键支持
                    this.setupKeyboardShortcuts();
                    
                    // 添加表单自动保存提示
                    this.setupFormChangeDetection();
                } catch (error) {
                    console.error('初始化失败:', error);
                    this.showNotification('页面初始化失败', 'error');
                }
            },
            
            // 加载客户数据
            async loadCustomer() {
                try {
                  
                    
                    const response = await fetch(`/api/v1/customers/${this.customerId}`, {
                        method: 'GET'
                    });
                    
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                    }
                    
                    const data = await response.json();
                    
                    if (data.code === 200) {
                        this.customer = data.data;
                        
                        // 填充表单数据
                        this.form = {
                            name: this.customer.name || '',
                            phone: this.customer.phone || '',
                            age: this.customer.age || '',
                            gender: this.customer.gender || '',
                            city: this.customer.city || '',
                            grade: this.customer.grade || '',
                            subject: this.customer.subject || '',
                            notes: this.customer.notes || ''
                        };
                        
                        // 保存原始数据用于比较
                        this.originalForm = { ...this.form };
                        this.initialLoading = false;
                        
                        this.showNotification('客户信息加载成功', 'success');
                    } else {
                        throw new Error(data.message || '加载客户信息失败');
                    }
                } catch (error) {
                    console.error('Failed to load customer:', error);
                    this.showNotification(error.message || '网络错误，请稍后重试', 'error');
                    setTimeout(() => window.location.href = '/customers', 2000);
                }
            },
            
            // 格式化日期
            formatDate(dateString) {
                if (!dateString) return '';
                const date = new Date(dateString);
                return date.toLocaleDateString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit'
                });
            },
            
            // 获取状态样式类
            getStatusClass(status) {
                const statusClasses = {
                    'active': 'bg-green-100 text-green-800',
                    'inactive': 'bg-gray-100 text-gray-800',
                    'pending': 'bg-yellow-100 text-yellow-800',
                    'blocked': 'bg-red-100 text-red-800'
                };
                return statusClasses[status] || 'bg-gray-100 text-gray-800';
            },
            
            // 获取状态文本
            getStatusText(status) {
                const statusTexts = {
                    'active': '活跃',
                    'inactive': '非活跃',
                    'pending': '待处理',
                    'blocked': '已屏蔽'
                };
                return statusTexts[status] || '未知';
            },
            
            // 获取字段样式类
            getFieldClass(fieldName) {
                if (this.errors[fieldName]) {
                    return 'border-red-300 focus:border-red-500 focus:ring-red-500';
                } else if (this.form[fieldName] && this.form[fieldName].toString().trim()) {
                    return 'border-green-300 focus:border-green-500 focus:ring-green-500';
                } else {
                    return 'border-gray-300 focus:border-blue-500 focus:ring-blue-500';
                }
            },
            
            // 实时验证单个字段
            validateField(fieldName) {
                // 清除该字段的错误
                if (this.errors[fieldName]) {
                    delete this.errors[fieldName];
                }
                
                const value = this.form[fieldName];
                
                switch (fieldName) {
                    case 'name':
                        if (!value || !value.trim()) {
                            this.errors.name = '请输入客户姓名';
                        } else if (value.trim().length < 2) {
                            this.errors.name = '姓名至少需要2个字符';
                        }
                        break;
                        
                    case 'phone':
                        if (!value || !value.trim()) {
                            this.errors.phone = '请输入手机号';
                        } else if (!this.isValidPhone(value.trim())) {
                            this.errors.phone = '请输入正确的手机号格式';
                        }
                        break;
                        
                    case 'city':
                        if (!value || !value.trim()) {
                            this.errors.city = '请输入所在城市';
                        }
                        break;
                        
                    case 'subject':
                        if (!value || !value.trim()) {
                            this.errors.subject = '请输入学习科目';
                        }
                        break;
                        
                    case 'age':
                        if (value && (value < 1 || value > 100)) {
                            this.errors.age = '年龄必须在1-100之间';
                        }
                        break;
                        
                    case 'notes':
                        if (value && value.length > 500) {
                            this.errors.notes = '备注信息不能超过500个字符';
                        }
                        break;
                }
            },
            
            // 验证手机号格式
            isValidPhone(phone) {
                return /^1[3-9]\d{9}$/.test(phone);
            },
            
            // 设置键盘快捷键
            setupKeyboardShortcuts() {
                document.addEventListener('keydown', (e) => {
                    // Ctrl+Enter 提交表单
                    if (e.ctrlKey && e.key === 'Enter') {
                        e.preventDefault();
                        if (this.isFormValid && !this.loading) {
                            this.submitForm();
                        }
                    }
                    
                    // Esc 键返回列表
                    if (e.key === 'Escape') {
                        e.preventDefault();
                        if (this.hasUnsavedChanges()) {
                            if (confirm('有未保存的更改，确定要离开吗？')) {
                                window.location.href = '/customers';
                            }
                        } else {
                            window.location.href = '/customers';
                        }
                    }
                });
            },
            
            // 设置表单变化检测
            setupFormChangeDetection() {
                // 监听页面离开事件
                window.addEventListener('beforeunload', (e) => {
                    if (this.hasUnsavedChanges()) {
                        e.preventDefault();
                        e.returnValue = '有未保存的更改，确定要离开吗？';
                        return e.returnValue;
                    }
                });
            },
            
            // 检查是否有未保存的更改
            hasUnsavedChanges() {
                if (!this.originalForm) return false;
                
                return Object.keys(this.form).some(key => {
                    const current = this.form[key] ? this.form[key].toString().trim() : '';
                    const original = this.originalForm[key] ? this.originalForm[key].toString().trim() : '';
                    return current !== original;
                });
            },
            
            // 显示通知
            showNotification(message, type = 'info') {
                // 移除现有通知
                const existingNotifications = document.querySelectorAll('.custom-notification');
                existingNotifications.forEach(n => n.remove());
                
                // 创建通知元素
                const notification = document.createElement('div');
                notification.className = `custom-notification fixed top-4 right-4 z-50 px-4 py-3 rounded-lg shadow-lg transition-all duration-300 transform translate-x-full max-w-sm`;
                
                const colors = {
                    success: 'bg-green-500 text-white border-green-600',
                    error: 'bg-red-500 text-white border-red-600',
                    info: 'bg-blue-500 text-white border-blue-600',
                    warning: 'bg-yellow-500 text-black border-yellow-600'
                };
                
                notification.className += ` ${colors[type] || colors.info}`;
                
                // 添加图标
                const icons = {
                    success: '✓',
                    error: '✕',
                    info: 'ℹ',
                    warning: '⚠'
                };
                
                notification.innerHTML = `
                    <div class="flex items-center space-x-2">
                        <span class="font-bold">${icons[type] || icons.info}</span>
                        <span>${message}</span>
                    </div>
                `;
                
                document.body.appendChild(notification);
                
                // 显示动画
                setTimeout(() => {
                    notification.classList.remove('translate-x-full');
                }, 100);
                
                // 自动隐藏
                setTimeout(() => {
                    notification.classList.add('translate-x-full');
                    setTimeout(() => {
                        if (notification.parentNode) {
                            notification.parentNode.removeChild(notification);
                        }
                    }, 300);
                }, type === 'error' ? 5000 : 3000); // 错误消息显示更长时间
            },
            
            // 批量验证表单
            validateForm() {
                // 清空之前的错误
                this.errors = {};
                
                // 验证所有字段
                const fields = ['name', 'phone', 'city', 'subject', 'age', 'notes'];
                fields.forEach(field => this.validateField(field));
                
                const isValid = Object.keys(this.errors).length === 0;
                
                if (!isValid) {
                    // 滚动到第一个错误字段
                    const firstErrorField = Object.keys(this.errors)[0];
                    const errorElement = document.querySelector(`[name="${firstErrorField}"]`);
                    if (errorElement) {
                        errorElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        errorElement.focus();
                    }
                }
                
                return isValid;
            },
            
            // 提交表单
            async submitForm() {
                if (!this.validateForm()) {
                    this.showNotification('请检查表单信息', 'error');
                    return;
                }
                
                // 检查是否有更改
                if (!this.hasUnsavedChanges()) {
                    this.showNotification('没有需要保存的更改', 'info');
                    return;
                }
                
                this.loading = true;
                
                try {
                 
                    
                    // 准备提交数据
                    const submitData = {
                        ...this.form,
                        age: this.form.age ? parseInt(this.form.age) : null
                    };
                    
                    const response = await fetch(`/api/v1/customers/${this.customerId}`, {
                        method: 'PUT',
                        body: JSON.stringify(submitData)
                    });
                    
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                    }
                    
                    const data = await response.json();
                    
                    if (data.code === 200) {
                        // 更新原始数据
                        this.originalForm = { ...this.form };
                        
                        this.showNotification('客户信息更新成功', 'success');
                        
                        // 延迟1.5秒后自动跳转到客户详情页面
                        setTimeout(() => {
                            window.location.href = `/customers/${this.customerId}`;
                        }, 1500);
                    } else {
                        // 处理服务器返回的错误
                        if (data.errors && typeof data.errors === 'object') {
                            this.errors = data.errors;
                            this.showNotification('表单验证失败，请检查输入', 'error');
                        } else {
                            throw new Error(data.message || '更新客户信息失败');
                        }
                    }
                } catch (error) {
                    console.error('Failed to update customer:', error);
                    this.showNotification(error.message || '网络错误，请稍后重试', 'error');
                } finally {
                    this.loading = false;
                }
            }
        }
    }
</script>
{{end}}